// 区域掩膜管理器
import type { DistrictData, DistrictStyle, MaskConfig } from './types'
import { createPolygon, clearOverlays } from './utils'

/**
 * 区域掩膜管理器类
 */
export class MaskManager {
  private map: any
  private maskPolygons: any[] = []
  private selectedPolygons: any[] = []
  private config: MaskConfig
  private isEnabled: boolean = true

  constructor(map: any, config: MaskConfig) {
    this.map = map
    this.config = config
    this.isEnabled = config.enableMask
  }

  /**
   * 更新掩膜配置
   */
  updateConfig(config: Partial<MaskConfig>) {
    this.config = { ...this.config, ...config }
    this.isEnabled = this.config.enableMask
  }

  /**
   * 启用/禁用掩膜效果
   */
  setEnabled(enabled: boolean) {
    this.isEnabled = enabled
    this.config.enableMask = enabled
    
    if (!enabled) {
      this.clearMask()
    }
  }

  /**
   * 创建全国掩膜效果
   * @param selectedDistricts 选中的区域列表
   * @param allDistricts 所有区域列表
   */
  async createCountryMask(
    selectedDistricts: DistrictData[],
    allDistricts: DistrictData[]
  ) {
    if (!this.isEnabled) return

    this.clearMask()

    // 创建选中区域的高亮多边形
    for (const district of selectedDistricts) {
      if (district.boundaries) {
        this.createSelectedPolygons(district)
      }
    }

    // 创建未选中区域的半透明多边形
    const unselectedDistricts = allDistricts.filter(
      district => !selectedDistricts.some(selected => selected.adcode === district.adcode)
    )

    for (const district of unselectedDistricts) {
      if (district.boundaries) {
        this.createMaskPolygons(district)
      }
    }
  }

  /**
   * 创建省级掩膜效果
   * @param selectedProvince 选中的省份
   * @param allProvinces 所有省份列表
   */
  async createProvinceMask(
    selectedProvince: DistrictData,
    allProvinces: DistrictData[]
  ) {
    if (!this.isEnabled) return

    this.clearMask()

    // 高亮选中的省份
    if (selectedProvince.boundaries) {
      this.createSelectedPolygons(selectedProvince)
    }

    // 其他省份半透明
    const otherProvinces = allProvinces.filter(
      province => province.adcode !== selectedProvince.adcode
    )

    for (const province of otherProvinces) {
      if (province.boundaries) {
        this.createMaskPolygons(province)
      }
    }
  }

  /**
   * 创建城市级掩膜效果
   * @param selectedCity 选中的城市
   * @param allCities 所有城市列表
   */
  async createCityMask(
    selectedCity: DistrictData,
    allCities: DistrictData[]
  ) {
    if (!this.isEnabled) return

    this.clearMask()

    // 高亮选中的城市
    if (selectedCity.boundaries) {
      this.createSelectedPolygons(selectedCity)
    }

    // 其他城市半透明
    const otherCities = allCities.filter(
      city => city.adcode !== selectedCity.adcode
    )

    for (const city of otherCities) {
      if (city.boundaries) {
        this.createMaskPolygons(city)
      }
    }
  }

  /**
   * 创建区县级掩膜效果
   * @param selectedDistrict 选中的区县
   * @param allDistricts 所有区县列表
   */
  async createDistrictMask(
    selectedDistrict: DistrictData,
    allDistricts: DistrictData[]
  ) {
    if (!this.isEnabled) return

    this.clearMask()

    // 高亮选中的区县
    if (selectedDistrict.boundaries) {
      this.createSelectedPolygons(selectedDistrict)
    }

    // 其他区县半透明
    const otherDistricts = allDistricts.filter(
      district => district.adcode !== selectedDistrict.adcode
    )

    for (const district of otherDistricts) {
      if (district.boundaries) {
        this.createMaskPolygons(district)
      }
    }
  }

  /**
   * 创建自定义掩膜效果
   * @param focusArea 焦点区域（高亮显示）
   * @param maskAreas 掩膜区域（半透明显示）
   */
  createCustomMask(
    focusArea: DistrictData | DistrictData[],
    maskAreas: DistrictData[]
  ) {
    if (!this.isEnabled) return

    this.clearMask()

    // 处理焦点区域
    const focusAreas = Array.isArray(focusArea) ? focusArea : [focusArea]
    for (const area of focusAreas) {
      if (area.boundaries) {
        this.createSelectedPolygons(area)
      }
    }

    // 处理掩膜区域
    for (const area of maskAreas) {
      if (area.boundaries) {
        this.createMaskPolygons(area)
      }
    }
  }

  /**
   * 创建选中区域的多边形（高亮显示）
   */
  private createSelectedPolygons(district: DistrictData) {
    district.boundaries.forEach((boundary, index) => {
      const polygon = createPolygon(this.map, boundary, this.config.selectedStyle)
      
      // 设置扩展数据
      polygon.setExtData({
        type: 'selected',
        district: district,
        boundaryIndex: index
      })

      // 绑定事件
      this.bindPolygonEvents(polygon, district, 'selected')
      
      this.selectedPolygons.push(polygon)
    })
  }

  /**
   * 创建掩膜区域的多边形（半透明显示）
   */
  private createMaskPolygons(district: DistrictData) {
    district.boundaries.forEach((boundary, index) => {
      const polygon = createPolygon(this.map, boundary, this.config.unselectedStyle)
      
      // 设置扩展数据
      polygon.setExtData({
        type: 'mask',
        district: district,
        boundaryIndex: index
      })

      // 绑定事件
      this.bindPolygonEvents(polygon, district, 'mask')
      
      this.maskPolygons.push(polygon)
    })
  }

  /**
   * 绑定多边形事件
   */
  private bindPolygonEvents(
    polygon: any,
    district: DistrictData,
    type: 'selected' | 'mask'
  ) {
    // 点击事件
    polygon.on('click', (e: any) => {
      this.onPolygonClick(polygon, district, type, e)
    })

    // 鼠标悬停事件
    polygon.on('mouseover', (e: any) => {
      this.onPolygonHover(polygon, district, type, true)
    })

    polygon.on('mouseout', (e: any) => {
      this.onPolygonHover(polygon, district, type, false)
    })
  }

  /**
   * 多边形点击事件处理
   */
  private onPolygonClick(
    polygon: any,
    district: DistrictData,
    type: 'selected' | 'mask',
    event: any
  ) {
    // 触发自定义事件
    this.map.emit('mask-polygon-click', {
      polygon,
      district,
      type,
      event
    })

    // 如果点击的是掩膜区域，可以将其设为选中状态
    if (type === 'mask') {
      this.switchToSelected(district)
    }
  }

  /**
   * 多边形悬停事件处理
   */
  private onPolygonHover(
    polygon: any,
    district: DistrictData,
    type: 'selected' | 'mask',
    isHover: boolean
  ) {
    if (isHover) {
      // 悬停时增强效果
      const hoverStyle = type === 'selected' 
        ? {
            ...this.config.selectedStyle,
            strokeWeight: (this.config.selectedStyle.strokeWeight || 2) + 1,
            fillOpacity: Math.min((this.config.selectedStyle.fillOpacity || 0.4) + 0.1, 1)
          }
        : {
            ...this.config.unselectedStyle,
            strokeWeight: (this.config.unselectedStyle.strokeWeight || 1) + 1,
            fillOpacity: Math.min((this.config.unselectedStyle.fillOpacity || 0.2) + 0.1, 1)
          }
      
      polygon.setOptions(hoverStyle)
      
      // 显示提示信息
      this.showTooltip(district, polygon)
    } else {
      // 恢复原样式
      const originalStyle = type === 'selected' 
        ? this.config.selectedStyle 
        : this.config.unselectedStyle
      
      polygon.setOptions(originalStyle)
      
      // 隐藏提示信息
      this.hideTooltip()
    }
  }

  /**
   * 将掩膜区域切换为选中状态
   */
  private switchToSelected(district: DistrictData) {
    // 移除该区域的掩膜多边形
    this.maskPolygons = this.maskPolygons.filter(polygon => {
      const extData = polygon.getExtData()
      if (extData.district.adcode === district.adcode) {
        polygon.setMap(null)
        return false
      }
      return true
    })

    // 创建选中状态的多边形
    this.createSelectedPolygons(district)

    // 触发切换事件
    this.map.emit('mask-switch-selected', { district })
  }

  /**
   * 显示提示信息
   */
  private showTooltip(district: DistrictData, polygon: any) {
    if (!window.AMap) return

    const content = `
      <div style="
        padding: 8px 12px;
        background: rgba(0, 0, 0, 0.8);
        color: white;
        border-radius: 4px;
        font-size: 12px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
      ">
        <div style="font-weight: bold; margin-bottom: 4px;">${district.name}</div>
        <div style="opacity: 0.8;">代码: ${district.adcode}</div>
        <div style="opacity: 0.8;">级别: ${district.level}</div>
      </div>
    `

    const tooltip = new window.AMap.InfoWindow({
      content: content,
      offset: new window.AMap.Pixel(0, -10),
      closeWhenClickMap: false,
      autoMove: true
    })

    // 获取多边形中心点
    const bounds = polygon.getBounds()
    const center = bounds.getCenter()
    
    tooltip.open(this.map, center)
    
    // 保存引用
    this.currentTooltip = tooltip
  }

  private currentTooltip: any = null

  /**
   * 隐藏提示信息
   */
  private hideTooltip() {
    if (this.currentTooltip) {
      this.currentTooltip.close()
      this.currentTooltip = null
    }
  }

  /**
   * 更新选中区域样式
   */
  updateSelectedStyle(style: Partial<DistrictStyle>) {
    this.config.selectedStyle = { ...this.config.selectedStyle, ...style }
    
    // 更新现有的选中多边形样式
    this.selectedPolygons.forEach(polygon => {
      polygon.setOptions(this.config.selectedStyle)
    })
  }

  /**
   * 更新掩膜区域样式
   */
  updateMaskStyle(style: Partial<DistrictStyle>) {
    this.config.unselectedStyle = { ...this.config.unselectedStyle, ...style }
    
    // 更新现有的掩膜多边形样式
    this.maskPolygons.forEach(polygon => {
      polygon.setOptions(this.config.unselectedStyle)
    })
  }

  /**
   * 获取选中的区域
   */
  getSelectedDistricts(): DistrictData[] {
    return this.selectedPolygons.map(polygon => {
      const extData = polygon.getExtData()
      return extData.district
    })
  }

  /**
   * 获取掩膜区域
   */
  getMaskDistricts(): DistrictData[] {
    return this.maskPolygons.map(polygon => {
      const extData = polygon.getExtData()
      return extData.district
    })
  }

  /**
   * 清除所有掩膜效果
   */
  clearMask() {
    // 清除选中多边形
    clearOverlays(this.map, this.selectedPolygons)
    
    // 清除掩膜多边形
    clearOverlays(this.map, this.maskPolygons)
    
    // 隐藏提示信息
    this.hideTooltip()
  }

  /**
   * 调整地图视野以包含所有多边形
   */
  fitView() {
    const allPolygons = [...this.selectedPolygons, ...this.maskPolygons]
    if (allPolygons.length > 0) {
      this.map.setFitView(allPolygons)
    }
  }

  /**
   * 获取掩膜配置
   */
  getConfig(): MaskConfig {
    return { ...this.config }
  }

  /**
   * 销毁掩膜管理器
   */
  destroy() {
    this.clearMask()
    this.map = null
  }
}